<script setup lang="ts">
import { Delete, Edit } from "@element-plus/icons-vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElCol,
  ElRow,
  ElTag,
  ElCard,
  ElButton,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn,
} from "element-plus";

import { ProInputNumber, ProRadioGroup } from "@/modules/package/form";
import DialogPackageCoupon from "./components/DialogPackageCoupon.vue";
import AppFooter from "@/components/common/AppFooter.vue";

import { find, isNumber } from "lodash-es";
import { useRoute, useRouter } from "vue-router";

import ApiActivity from "@/api/activity";
import useEnum from "@/hooks/useEnum";
import useForm from "@/hooks/useForm";
import useDialog from "@/hooks/useDialog";
import useRequest from "@/hooks/useRequest";

import { EnumRuleOptions, EnumStatus } from "@/utils/enum";
import { TPackage } from "@/types/global";
import EnumTag from "@/components/common/EnumTag.vue";
import { computed } from "vue";

const { params } = useRoute();

const { get: getStatus } = useEnum("EnumStatus");
const { list: listStatus } = useEnum("EnumStatus");

const {
  refForm,
  model,
  isFetching: isSubmiting,
  reset,
  submit,
  onFetchResponse,
} = useForm<TPackage>(ApiActivity[params.id ? "packageEdit" : "packageAdd"], {
  defaultModel: {
    sort: 99,
    status: 1,
    coupons: [],
  },
});

// 获取权益模板详情
const {
  isFetching: isFetchingWithDetail,
  data: packageDetail,
  onFetchResponse: onFetchResponseWithDetail,
} = useRequest(ApiActivity.packageDetail, {
  immediate: !!params.id,
  defaultParams: { id: +params.id },
});
onFetchResponseWithDetail(() => {
  const { detail } = packageDetail.value;

  model.value = {
    ...detail,
  };
});

const router = useRouter();
onFetchResponse(() => {
  ElMessage.success("操作成功！");
  router.go(-1);
});

const rules = {
  package_title: { required: true, message: "请输入权益包标题" },
  sort: { required: true, message: "请输入排序" },
  status: { required: true, message: "请输入权益包标题" },
  specs: {
    required: true,
    message: "请设置规则",
    validator(_: any, values: any, callback: any) {
      if (values.length > 0) {
        callback();
      } else {
        callback(new Error("请设置规则  "));
      }
    },
  },
};

// 添加票券弹窗
const [visible, { source, open, close }] = useDialog<number>();

const confirmCoupon = (data: any) => {
  let coupons = model.value.coupons || [];
  const index = source.value;

  if (isNumber(index) && index >= 0) {
    // 编辑
    coupons[index] = data;
  } else {
    // 新增
    coupons.push(data);
  }

  model.value.coupons = coupons;
  close();
};

const confimSubmit = () => {
  console.log(model.value);
  submit();
};

/**
 * 删除权益
 * @param index
 */
const handleDelete = async (index: number) => {
  await ElMessageBox.confirm("是否确认删除该权益？", "提示");
  model.value.coupons.splice(index, 1);
};

// 表格：展示生效规则内容
const findRuleTypeText = ({
  rule_type,
  rule_condition,
}: TPackage["coupons"][number]["rules"][number]) => {
  const parent = find(EnumRuleOptions, { value: rule_type });
  const child = find(parent?.children, { value: "" + rule_condition });

  console.log("parent", rule_type, parent);
  console.log("child", rule_condition, child);

  return parent?.label + " -\n" + child?.label;
};

const couponTableData = computed(() => {
  const { coupons = [] } = model.value;

  return coupons
    .map((e) => {
      const { rules, ...rest } = e;
      const spanCount = rules.length;

      return rules.map((e, index) => {
        const parent = find(EnumRuleOptions, { value: e.rule_type });
        const child = find(parent?.children, { value: "" + e.rule_condition });

        return {
          ...rest,
          spanCount: index === 0 ? spanCount : 0,
          rule: {
            type: parent?.label + " -\n" + child?.label,
            content: e.rule_content + (child?.unit || ""),
          },
        };
      });
    })
    .flat(2);
});

// 合并表格
function handleSpanMethod({ row, columnIndex }: any) {
  if ([0, 1, 2, 5].includes(columnIndex)) {
    //  [rowspan，colspan]
    return [row.spanCount, row.spanCount ? 1 : 1];
  }
  return [1, 1];
}
</script>

<template>
  <AppFooter>
    <div class="py-3 text-center">
      <ElButton plain size="large" :disabled="isSubmiting" @click="reset"
        >重置</ElButton
      >
      <ElButton
        type="primary"
        size="large"
        :loading="isSubmiting"
        @click="confimSubmit"
        >保存</ElButton
      >
    </div>
  </AppFooter>

  <ElForm
    ref="refForm"
    :model="model"
    label-width="9em"
    :rules="rules"
    v-loading="isFetchingWithDetail"
  >
    <ElCard header="基本信息">
      <ElFormItem label="权益包模板标题" prop="package_title">
        <ElInput v-model="model.package_title" />
      </ElFormItem>

      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="状态" prop="status">
            <ProRadioGroup v-model="model.status" :options="listStatus" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="排序" prop="sort">
            <ProInputNumber
              v-model="model.sort"
              :min="1"
              :max="9999"
              :precision="0"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="model.remark" />
      </ElFormItem>
    </ElCard>

    <ElCard header="关联权益" class="mt-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>关联权益</span>
          <ElButton type="primary" @click="open()">添加权益</ElButton>
        </div>
      </template>

      <ElTable :data="couponTableData" border :span-method="handleSpanMethod">
        <ElTableColumn label="票券" prop="coupon_name" width="130" />
        <ElTableColumn label="数量" prop="num" width="60" />
        <ElTableColumn label="状态" prop="status" width="70">
          <template #="{ row }">
            <EnumTag :value="row.status" :options="EnumStatus" />
          </template>
        </ElTableColumn>

        <!-- <ElTableColumn label="排序" prop="sort" width="60" /> -->
        <!-- <ElTableColumn label="备注" prop="remark" width="120" /> -->

        <ElTableColumn label="规则">
          <ElTableColumn label="生效规则" prop="rule.type" />
          <ElTableColumn label="内容" prop="rule.content" />
        </ElTableColumn>

        <ElTableColumn label="操作" width="110">
          <template #="{ $index }">
            <ElButton
              :icon="Edit"
              type="primary"
              circle
              plain
              @click="open($index)"
            />
            <ElButton
              :icon="Delete"
              type="danger"
              circle
              plain
              @click="handleDelete($index)"
            />
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
  </ElForm>

  <DialogPackageCoupon
    v-if="visible"
    :couponSource="model.coupons?.[source]"
    @confirm="confirmCoupon"
    @close="close"
  />
</template>
